<?php

class controller extends controllerBase {

	public function add()
	{
		global $headers;
		$title = 'add page';
		
		$errors = array();
		
		if(isset($_POST['submit']))
		{
			$page = new page();
			
			#check title
			if($_POST['title'] == '')
			{
				$errors[] = 'no-title';
			}
			else
			{
				$page->title = $_POST['title'];
			}
			
			#check content
			if($_POST['content'] == '')
			{
				$errors[] = 'no-content';
			}
			else
			{
				$page->content = $_POST['content'];
			}
			
			#check url
			if($_POST['url'] == '')
			{
				$errors[] = 'no-url';
			}
			else
			{
				$page->url = $_POST['url'];
			}
			
			if(count($errors) <= 0)
			{
				$page->save();
				
				unset($_POST);
				$submitted = true;
			}
		}
		
		if($submitted)
		{
			$content = "page added";
		}
		else
		{
			$content = form::getForm('page_add', array($errors));
		}
		
		include(ROOT . 'admin/skin/wrapper.php');
	}
	
	public function edit($id = '')
	{
		global $headers;
		$title = 'edit page';
		if($id == "")	//no page set, show all
		{
			$query = new Query("SELECT * FROM `pages` ORDER BY `id` DESC");
			
			if($query->num_rows() > 0)
			{
				$pages = page::RecordSet($query, 'page');
				
				for($i = 0; $i < count($pages); $i++)
				{
					$content .= '<p>' . $pages[$i]->title . ' : <a href="' . ROOT_URL .'admin/index.php/page/edit/' . $pages[$i]->id . '">Edit</a> - <a href="' . ROOT_URL .'admin/index.php/page/delete/' . $pages[$i]->id . '">Delete</a></p>';
				}
			}
			else
			{
				$content .= 'There are currently no pages.';
			}
		}
		else	//get that specific page for editing
		{
			$page = new page($id);
			$title .=' :: ' . stripslashes($page->title);
			
			$errors = array();
			
			if($_POST['submit'])
			{
				#check title
				if($_POST['title'] == '')
				{
					$errors[] = 'no-title';
				}
				else
				{
					$page->title = $_POST['title'];
				}
				
				#check content
				if($_POST['content'] == '')
				{
					$errors[] = 'no-content';
				}
				else
				{
					$page->content = $_POST['content'];
				}
				
				#check url
				if($_POST['url'] == '')
				{
					$errors[] = 'no-url';
				}
				else
				{
					$page->url = $_POST['url'];
				}
				
				if(count($errors) <= 0)
				{
					$page->save();
					
					unset($_POST);
					$submitted = true;
				}
			}
			
			if($submitted)
			{
				$content .= 'page updated';
			}
			else
			{
				$content .= form::getForm('page_edit', array($errors, $page));
			}
		}
		include(ROOT . 'admin/skin/wrapper.php');
	}
	
	public function delete($id = '')
	{
		if($id != '')
		{
			$query = new Query("DELETE FROM `pages` WHERE `id` = ?", $id);
			
			$content = 'page deleted';
		}
		
		include(ROOT . 'admin/skin/wrapper.php');
	}
}
?>